//
//  LYBalanceViewController.m
//  Btpin
//
//  Created by liuyan on 2019/4/21.
//  Copyright © 2019年 Vic. All rights reserved.
//

#import "LYBalanceViewController.h"
#import "LYIncomBreakDownCell.h"
#import "LYSegmentView.h"

#import "LYWithdrawController.h"
#import "LYExchangeCoinsViewController.h"

@interface LYBalanceViewController ()<UITableViewDelegate, UITableViewDataSource, LYSegmentViewDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *allDataArray;
@property (nonatomic, strong) NSMutableArray *incomeDataArray;
@property (nonatomic, strong) NSMutableArray *expendDataArray;
@property (nonatomic, strong) UILabel *balanceLabel;

@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UIButton *withDrawBtn;
@property (nonatomic, strong) UIButton *exchangeBtn;

@end

@implementation LYBalanceViewController

- (NSMutableArray *)allDataArray {
    if (!_allDataArray) {
        _allDataArray = [NSMutableArray array];
    }
    return _allDataArray;
}
- (NSMutableArray *)incomeDataArray {
    if (!_incomeDataArray) {
        _incomeDataArray = [NSMutableArray array];
    }
    return _incomeDataArray;
}
- (NSMutableArray *)expendDataArray {
    if (!_expendDataArray) {
        _expendDataArray = [NSMutableArray array];
    }
    return _expendDataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    [self createSubview];
    [self requestListData];
    [self pullDownAndUpRefresh];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
    [self pullDown];
}
- (void)createSubview {
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = RGB(247, 247, 247);
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.tableview registerClass:[LYIncomBreakDownCell class] forCellReuseIdentifier:kCellIdentifier_LYIncomBreakDownCell];
    [self.view addSubview:self.tableview];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 160)];
    header.backgroundColor = [UIColor orangeColor];
    self.tableview.tableHeaderView = header;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, WIDTH - 110, 25)];
    titleLabel.text = @"我的余额（元）";
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    titleLabel.textColor = [UIColor whiteColor];
    [header addSubview:titleLabel];
    
    self.balanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, titleLabel.bottom +5, WIDTH - 110, 40)];
    self.balanceLabel.text = @"0";
    self.balanceLabel.font = [UIFont boldSystemFontOfSize:28];
    self.balanceLabel.textColor = [UIColor whiteColor];
    [header addSubview:self.balanceLabel];
    
    self.exchangeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [header addSubview:self.exchangeBtn];
    self.exchangeBtn.frame = CGRectMake(WIDTH -95, 10,82, 20);
    [self.exchangeBtn addTarget:self action:@selector(exchangeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.exchangeBtn setTitle:@"兑换聘豆 >>" forState:UIControlStateNormal];
    [self.exchangeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.exchangeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    
    if ([UD_GetOForK(isUserRole) isEqualToString:@"2"]) {
        self.withDrawBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [header addSubview:self.withDrawBtn];
        self.withDrawBtn.frame = CGRectMake(WIDTH -95,  self.exchangeBtn.bottom+15 ,82, 30);
        [self.withDrawBtn addTarget:self action:@selector(withDrawBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.withDrawBtn.layer.cornerRadius = self.withDrawBtn.height/2;
        self.withDrawBtn.clipsToBounds = YES;
        self.withDrawBtn.layer.borderWidth = 1;
        self.withDrawBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        self.withDrawBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
        [self.withDrawBtn setTitle:@" 去提现" forState:UIControlStateNormal];
        [self.withDrawBtn setImage:[UIImage imageNamed:@"qianbao-tixian"] forState:UIControlStateNormal];
        [self.withDrawBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.withDrawBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    }
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 90, WIDTH, 70)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [header addSubview:bottomView];
    
    LYSegmentView *segmentView = [[LYSegmentView alloc] initWithFrame:CGRectMake((WIDTH - 160)/2, 10, 180, 30)];
    segmentView.delegate = self;
    self.selectIndex = 0;
    [segmentView setSegmentWithBackground:COLOR_OF_WHITE titleArray:@[@"全部", @"获得", @"支出"] titleFont:Font(Font_15) titleLineSelectColor:THEMECOLOR_OF_TEXT_333333 normal:THEMECOLOR_OF_TEXT_9a9a9a withselectedIndex:0];
    [bottomView addSubview:segmentView];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 40, 40, 30)];
    leftLabel.text = @"名称";
    leftLabel.font = [UIFont boldSystemFontOfSize:14];
    leftLabel.textColor = RGB(34, 34, 34);;
    [bottomView addSubview:leftLabel];
    
    UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH-55, 40, 40, 30)];
    rightLabel.text = @"金额";
    rightLabel.textAlignment = NSTextAlignmentRight;
    rightLabel.font = [UIFont boldSystemFontOfSize:14];
    rightLabel.textColor = RGB(34, 34, 34);
    [bottomView addSubview:rightLabel];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selectIndex == 0) {
        return self.allDataArray.count;
    }else if (self.selectIndex == 1){
        return self.incomeDataArray.count;
    }else{
        return self.expendDataArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LYIncomBreakDownCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYIncomBreakDownCell forIndexPath:indexPath];
    if (self.selectIndex == 0) {
        cell.expendDic =  self.allDataArray[indexPath.row];
    }else if (self.selectIndex == 1){
        cell.expendDic =  self.incomeDataArray[indexPath.row];
    }else{
        cell.expendDic =  self.expendDataArray[indexPath.row];
    }
    return cell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0f;
}
#pragma mark-- loadData
- (void)requestData {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_amount_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            //钱包信息
            CGFloat amount = [responseObject[@"data"][@"amount"] floatValue];
            weakSelf.balanceLabel.text = [NSString stringWithFormat:@"%.2f",amount];
            NSString *str = weakSelf.balanceLabel.text;
            if ([[str substringFromIndex:str.length-2] isEqualToString:@"00"]) {
                str = [str substringToIndex:str.length-3];
                weakSelf.balanceLabel.text = str;
            } else if ([[str substringFromIndex:str.length-1] isEqualToString:@"0"]) {
                weakSelf.balanceLabel.text = [str substringToIndex:str.length-1];
            }
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)pullDownAndUpRefresh {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullDown)];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.textColor = RGB(85, 85, 85);
    [header setTitle:@"下拉刷新..." forState:MJRefreshStateIdle];
    [header setTitle:@"松手刷新..." forState:MJRefreshStatePulling];
    [header setTitle:@"拼命加载中..." forState:MJRefreshStateRefreshing];
    self.tableview.mj_header = header;
    //    //上啦加载
    __weak typeof(self) weakSelf = self;
    MJRefreshAutoNormalFooter *footer =  [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf pullUp];
    }];
    footer.stateLabel.textColor = RGB(153, 153, 153);
    self.tableview.mj_footer = footer;
}
/**
 下拉
 */
- (void)pullDown{
    self.page = 1;
    [self requestListData];
}
- (void)pullUp{
    self.page ++;
    [self requestListData];
}
- (void)requestListData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    //0不限 1 收入 2支出
    dic[@"typeid"] = [NSNumber numberWithInteger:self.selectIndex];
    dic[@"page"] = [NSNumber numberWithInteger:self.page];
    dic[@"number"] = @10;
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_getAccountLogs_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            //收入信息信息
            [weakSelf organizeData:responseObject[@"data"]];
        }else{
            SVPHUDError(responseObject[@"msg"]);
            [self pullUpFail];
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
        [self pullUpFail];
    }];
}
/**
 上拉失败，pagenum不增加
 */
- (void)pullUpFail{
    //上拉
    if (self.page > 1) {
        self.page --;
    }
    [self.tableview.mj_footer endRefreshing];
    [self.tableview.mj_header endRefreshing];
}
- (void)organizeData:(NSDictionary *)dataDic{
    if (self.page == 1 && self.allDataArray.count) {
        [self.allDataArray removeAllObjects];
    }
    
    if (self.page == 1 && self.incomeDataArray.count) {
        [self.incomeDataArray removeAllObjects];
    }
    
    if (self.page == 1 && self.expendDataArray.count) {
        [self.expendDataArray removeAllObjects];
    }
    
    NSArray *array = dataDic[@"logs"];
    if (array.count == 0) {
        [self.tableview.mj_footer endRefreshingWithNoMoreData];
    }else{
        for (NSDictionary *dic in array) {
            if (self.selectIndex == 0) {
                [self.allDataArray addObject:dic];
            }else if (self.selectIndex == 1){
                [self.incomeDataArray addObject:dic];
            }else{
                [self.expendDataArray addObject:dic];
            }
        }
        [self.tableview.mj_footer endRefreshing];
    }
    [self.tableview reloadData];
    [self.tableview.mj_header endRefreshing];
}
#pragma mark -- Action
- (void)customSegmentedValueChanged:(UISegmentedControl *)segment{
    self.selectIndex = segment.selectedSegmentIndex;
    [self pullDown];
}
- (void)withDrawBtnClick:(UIButton *)button{
    LYWithdrawController *withDrawVC = [[LYWithdrawController alloc] init];
    [self.navigationController pushViewController:withDrawVC animated:YES];
}
- (void)exchangeBtnClick:(UIButton *)button{
    LYExchangeCoinsViewController *exchangeVC = [[LYExchangeCoinsViewController alloc] init];
    [self.navigationController pushViewController:exchangeVC animated:YES];
}

@end
